13 Java Tutorial > 13.2 Programming the MIDlet > 13.2.2 Example

13.2.2
/* This example derives a class from Thread and creates two instances
* of the subclass. One thread instance finishes itself, the other one
* is stopped by the main application. */
 
package example.threaddemo;
import javax.microedition.midlet.*;
public class ThreadDemo extends MIDlet {
/* Member variables */
boolean runThreads = true; // Flag for stopping threads
DemoThread thread1; // First instance of DemoThread
DemoThread thread2; // Second instance of DemoThread
 
/* Private class implementing the thread to be started by the
* main application */
private class DemoThread extends Thread {
int loops;
 
public DemoThread(int waitTime) {
/* Store number of loops to execute */
loops = waitTime;
System.out.println("Thread(" + loops + "): Created");
}
 
public void run() {
System.out.println("Thread(" + loops + "): Started");
for (int i = 1; i <= loops; i++) {
/* Check if main application asked thread to die */
if (runThreads != true) {
System.out.println("Thread(" + loops + "): Stopped from outside");
/* Leave thread */
return;
}
/* Print loop counter and wait 1 second,
* do something useful here instead */
System.out.println("Thread(" + loops + "): Loop " + i);
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
System.out.println(e);
}
}
System.out.println("Thread(" + loops + "): Finished naturally");
}
}
/**
* ThreadDemo - constructor
*/
public ThreadDemo() {
System.out.println("ThreadDemo: Constructor, creating threads");
thread1 = new DemoThread(2);
thread2 = new DemoThread(6);
}
/**
* startApp()
*/
public void startApp() throws MIDletStateChangeException {
System.out.println("ThreadDemo: startApp, starting threads");
thread1.start();
thread2.start();
System.out.println("ThreadDemo: Waiting 4 seconds before stopping threads");
try {
Thread.sleep(4000);
} catch(InterruptedException e) {
System.out.println(e);
}
destroyApp(true);
System.out.println("ThreadDemo: Closing application");
}
/**
* pauseApp()
*/
public void pauseApp() {
System.out.println("ThreadDemo: pauseApp()");
}
/**
* destroyApp()
*/
public void destroyApp(boolean cond) {
System.out.println("ThreadDemo: destroyApp(" + cond + ")");
System.out.println("ThreadDemo: Stopping threads from outsdide");
runThreads = false;
try {
System.out.println("ThreadDemo: Waiting for threads to die");
thread1.join();
thread2.join();
} catch(InterruptedException e) {
System.out.println(e);
}
System.out.println("ThreadDemo: All threads died");
notifyDestroyed();
}
}